package com.security.control.browser.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.security.control.core.support.AuthenticateResponseType;
import com.security.control.core.support.SimpleResponseEntity;
import com.security.control.core.properties.SecurityProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author imoot@gamil.com
 * @date 2018/12/18 0018 15:04
 */
@Component("myAuthenticationFailureHandler")
public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    private Logger log = LoggerFactory.getLogger(MyAuthenticationSuccessHandler.class);

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.info("登录失败");
        if (AuthenticateResponseType.JSON.equals(securityProperties.getBrowserProperties().getAuthenticateResponseType())) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());//设置失败后的状态码
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(new SimpleResponseEntity(exception.getMessage())));//返回失败异常信息
        } else {
            super.onAuthenticationFailure(request, response, exception);
        }
    }
}
